package com.opal.modules.costReportForm.service.impl;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.opal.consts.CommonConst;
import com.opal.consts.WSC;
import com.opal.domain.R;
import com.opal.domain.ReturnMessageData;
import com.opal.model.DataGridData;
import com.opal.modules.costReportForm.entity.*;
import com.opal.modules.costReportForm.entity.table.*;
import com.opal.modules.costReportForm.mapper.mysql.*;
import com.opal.modules.costReportForm.mapper.oracle.QueryManagerMapper;
import com.opal.modules.costReportForm.mapper.sqlServercpd.ArticlePrice;
import com.opal.modules.costReportForm.model.CartonPriceDetailsRecord;
import com.opal.modules.costReportForm.service.CartonDetailsService;
import com.opal.modules.costReportForm.service.CostReportFormService;
import com.opal.system.entity.table.OpalUser;
import com.opal.system.entity.table.OrgDeptExtend;
import com.opal.system.mapper.oracle.BdCustomerMapper;
import com.opal.utils.*;
import com.opal.vo.GrfTableVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Service
@Slf4j
public class CostReportFormServiceImpl implements CostReportFormService{

    @Autowired
    private CostReportInitialInfoMapperExtend costReportInitialInfoMapperExtend;
    @Autowired
    private CostReportInitialInfoMapper costReportInitialInfoMapper;
    @Autowired
    private CostReportMapper costReportMapper;
    @Autowired
    private CostReportAMapper costReportAMapper;
    @Autowired
    private CostReportBMapper costReportBMapper;
    @Autowired
    private CostReportCMapper costReportCMapper;
    @Autowired
    private BdCustomerMapper bdCustomerMapper;
    @Autowired
    private CostBhMapper costBhMapper;
    @Autowired
    private QueryManagerMapper queryManagerMapper;
    @Autowired
    private ArticlePrice articlePrice;
    @Autowired
    private CostReportOtherMapper costReportOtherMapper;
    @Autowired
    private CostReportBSinglehoursMapper costReportBSinglehoursMapper;
    @Autowired
    private CartonDetailsService cartonDetailsService;
    @Autowired
    private CostCommonMapper costCommonMapper;

    @Override
    public CostReport getCostReport(String costReportId) {
        return costReportMapper.selectByPrimaryKey(costReportId);
    }

    @Override
    public String selectName(String code) {
        return bdCustomerMapper.selectName(code);
    }

    @Override
    public String createGetcostReportId() {

        //获取部门：查询部门缩写

        String acronym = this.getDeptNano();
        if (acronym ==null){
            acronym="";
        }
        SimpleDateFormat sdf= new SimpleDateFormat("yyyyMM");
        String format = sdf.format(new Date());
        //查询数据是否有这个开头的版本号
        List<String> list = costReportMapper.getcostReportId(acronym+format+"%");

        //无：从0001开始加起
        Integer costReportId ;

        //若有：进行加1
        if(list !=null && list.size()>0){
            String var = list.get(0);
            var = var.replace(acronym, "");
            costReportId =Integer.parseInt(var)+1;
        }else {
            costReportId= Integer.parseInt(format + "0001");
        }
        String cRId= acronym+costReportId;
        //为此次成本报告单据先在数据库占位：防止用户同时处理的时候覆盖
        CostReport costReport = new CostReport();
        costReport.setCostReportId(cRId);
        costReport.setUserId(UserUtils.getSessionUserId());
        int i = costReportMapper.insertSelective(costReport);
        if(i>0){
            log.debug("为此次成本报告单据先在数据库占位："+costReport);
        }

        return cRId;
    }

    @Override
    public CostBhLayuiTable selectTimePriceService(CostBh costBh) {
        CostBhExample costBhExample = new CostBhExample();
        CostBhExample.Criteria criteria = costBhExample.createCriteria();
        if (costBh.getBhStatus() !=null){
            criteria.andBhStatusEqualTo(costBh.getBhStatus());
        }
        if (costBh.getBhId() !=null){
            criteria.andBhIdEqualTo(costBh.getBhId());
        }
        //根据用户的组织条件查询
        criteria.andPkOrgEqualTo(UserUtils.getSessionUser().getPkOrg());
        List<CostBh> costBhs = costBhMapper.selectByExample(costBhExample);
        //layui需要的数据
        CostBhLayuiTable costBhLayuiTable = new CostBhLayuiTable();
        costBhLayuiTable.setCode(0);
        costBhLayuiTable.setData(costBhs);
        return costBhLayuiTable;
    }

    @Override
    @Transactional(value = "mysqlTransactionManager")
    public Object addTimePriceService(CostBh costBh) {
        try {
            if (modifyPriceStatus()){
                //设置值
                costBh.setBhStatus(true);       //默认都是有效状态
                costBh.setBhTake(new Date());   //生效时间
                //需要分权限组织 2020年3月23日
                costBh.setPkOrg(UserUtils.getSessionUser().getPkOrg());
                int i =costBhMapper.insertSelective(costBh);
                if (i>0){
                    return  new ReturnMessageData(200, "更换成功", this.selectTimePriceService(new CostBh()));
                }else {
                    throw new RuntimeException("更换单价工时失败");
                }
            }else {
                throw new RuntimeException("更换单价工时状态失败");
            }

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
           return new ReturnMessageData(500, "更换失败，系统或维护中，请稍后再尝试！");
        }

    }

    //在插入之前先进行更改状态
    private Boolean modifyPriceStatus() {
        try {
            //条件设置：状态为true可用
            CostBhExample costBhExample = new CostBhExample();
            CostBhExample.Criteria criteria = costBhExample.createCriteria();
            criteria.andBhStatusEqualTo(true);
            criteria.andPkOrgEqualTo(UserUtils.getSessionUser().getPkOrg());
            //要修改的状态
            CostBh costBh = new CostBh();
            costBh.setBhStatus(false);
            costBh.setBhLose(new Date());
            costBhMapper.updateByExampleSelective(costBh,costBhExample);
            return true;
        }catch (Exception e){
           e.printStackTrace();
           return false;
        }

    }

    @Override
    public Object modifyTimePriceService(CostBh costBh) {
        //若状态为空：把状态设置为失效状态，失效时间
        if (costBh.getBhStatus()==null){
            costBh.setBhStatus(false);
            costBh.setBhLose(new Date());
        }
        try {
            int i=costBhMapper.updateByPrimaryKeySelective(costBh);
            if (i>0){
                return  new ReturnMessageData(200, "修改成功");
            }else {
                return  new ReturnMessageData(400, "修改失败，没有指定要修改的值！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnMessageData(500, "修改失败，系统或维护中，请稍后再尝试！");
        }
    }

    @Override
    public Object costPswhAddService(CostReportInitialInfo costReportInitialInfo) {
        try {
            //需要分权限组织 2020年3月23日
            costReportInitialInfo.setPkOrg(UserUtils.getSessionUser().getPkOrg());
            //若父亲id为0或工时为0都把工时设置为null
            if(costReportInitialInfo.getSuperId()==0 || costReportInitialInfo.getSlManHour().equals("0")){
                costReportInitialInfo.setSlManHour(null);
            }
            //若序号为-1设置为null
            if(costReportInitialInfo.getNum()==-1){
                costReportInitialInfo.setNum(null);
            }
            int i=costReportInitialInfoMapper.insertSelective(costReportInitialInfo);

            if (i>0){
                return  new ReturnMessageData(200, "插入成功",this.selectAll2(costReportInitialInfo.getInitialType()));
            }else {
                return  new ReturnMessageData(400, "插入失败，没有指定要修改的值！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnMessageData(500, "插入失败，系统或维护中，请稍后再尝试！");
        }

    }

    //递归删除
    @Override
    @Transactional(value = "mysqlTransactionManager",rollbackFor = {Exception.class})
    public Object costPswhDelService(Integer id) {
        //查询是否有子元素
        try {
            CostReportInitialInfoExample cri= new CostReportInitialInfoExample();
            CostReportInitialInfoExample.Criteria criteria = cri.createCriteria();
            criteria.andSuperIdEqualTo(id);
            List<CostReportInitialInfo> costReportInitialInfos = costReportInitialInfoMapper.selectByExample(cri);
            if (costReportInitialInfos.size()>0) {
                for (CostReportInitialInfo costReportInitialInfo : costReportInitialInfos) {
                    //递归调用
                    costPswhDelService(costReportInitialInfo.getSubId());
                }
            }
            //直到没有则把自己删除
            costReportInitialInfoMapper.deleteByPrimaryKey(id);
            return  new ReturnMessageData(200, "删除成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return new ReturnMessageData(500, "删除失败，系统或维护中，请稍后再尝试！");
        }
    }

    @Override
    public Object costPswhUpdateService(CostReportInitialInfo costReportInitialInfo) {
        try {
            int i=costReportInitialInfoMapper.updateByPrimaryKeySelective(costReportInitialInfo);

            if (i>0){
                return  new ReturnMessageData(200, "修改成功");
            }else {
                return  new ReturnMessageData(400, "修改失败，没有指定要修改的值！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnMessageData(500, "修改失败，系统或维护中，请稍后再尝试！");
        }
    }

    @Override
    public Object getPriceHoursService() {
        CostBhExample costBhExample = new CostBhExample();
        CostBhExample.Criteria criteria = costBhExample.createCriteria();
        //条件不能是false
        criteria.andBhStatusEqualTo(true).andBhLoseIsNull().andPkOrgEqualTo(UserUtils.getSessionUser().getPkOrg());
        List<CostBh> costBhs = costBhMapper.selectByExample(costBhExample);
        return costBhs.get(0).getBhPrice();
    }

    @Override
    public List<CostReportInitialInfoEayui> selectAll(int type, String typeName,String num,String pkOrg) {
        if (!StringUtils.isBlank(typeName)){
            typeName="%"+typeName+"%";
        }
        if (StringUtils.isBlank(pkOrg)){
            pkOrg=UserUtils.getSessionUser().getPkOrg();
        }
        List<CostReportInitialInfoEayui> costReportInitialInfoList = costReportInitialInfoMapperExtend.selectAll(type,pkOrg,typeName,num);
        return costReportInitialInfoList;
    }

    @Override
    public List<CostReportInitialInfoLayui> selectAll2(int type) {
        List<CostReportInitialInfoLayui> costReportInitialInfoList = costReportInitialInfoMapperExtend.selectAll2(type,UserUtils.getSessionUser().getPkOrg());
        List<CostReportInitialInfoLayui> paternalResult = new ArrayList<>();
        Map<Integer,CostReportInitialInfoLayui> map= new HashMap<>();
        for (CostReportInitialInfoLayui info : costReportInitialInfoList) {
            map.put(info.getSubId(),info);
            if (info.getSuperId() == 0) {
                //父菜单
                paternalResult.add(info);
            }
        }
        for (CostReportInitialInfoLayui innerInfo : costReportInitialInfoList) {
            //根据付清id找付清
            CostReportInitialInfoLayui costReportInitialInfoLayui = map.get(innerInfo.getSuperId());
            if (costReportInitialInfoLayui !=null) {
                costReportInitialInfoLayui.setState("closed");//关闭
                costReportInitialInfoLayui.getChildren().add(innerInfo);
            }
        }
        return paternalResult;
    }

    @Override
    @Transactional("mysqlTransactionManager")
    public ResultMsg updataCostReport(CostReport costReport) {
        try {
            costReportMapper.updateByPrimaryKeySelective(costReport);
            return new ResultMsg(WSC.RESTPONSE_OK, "成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultMsg(WSC.REQUEST_ERROR, "错误");
        }
    }

    @Override
    @Transactional("mysqlTransactionManager")
    public ReturnMessageData costReportUpdate(List<CostReportA> costReportA, String costReportId) {
        return null;
    }

    @Override
    public ReturnMessageData costReportBUpdate(List<CostReportB> costReportB, String costReportId) {
        return null;

    }

    @Override
    public ReturnMessageData costReportCUpdate(List<CostReportC> costReportC, String costReportId) {
        return null;
    }

    @Override
    public ReturnMessageData costReportASelect(String costReportId) {
        List<CostReportA> costReportAList = costReportAMapper.selectByPrimaryKey(costReportId);
        return new ReturnMessageData(200, null, costReportAList);
    }

    @Override
    @Transactional("mysqlTransactionManager")
    public Map costReportADetele(Integer id) {
        Map map = new HashMap();
        try {
            costReportAMapper.deleteByPrimaryKey(id);
            map.put("success", true);
            return map;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("success", false);
            return map;
        }
    }

    @Override
    @Transactional("mysqlTransactionManager")
    public Map costReportBDetele(Integer id) {
        Map map = new HashMap();
        try {
            costReportBMapper.deleteByPrimaryKey(id);
            map.put("success", true);
            return map;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("success", false);
            return map;
        }
    }

    @Override
    @Transactional("mysqlTransactionManager")
    public Map costReportCDetele(Integer id) {
        Map map = new HashMap();
        try {
            costReportCMapper.deleteByPrimaryKey(id);
            map.put("success", true);
            return map;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("success", false);
            return map;
        }
    }

    @Override
    public GrfTableVO<Map> getCostReportGrf(String banben) throws IllegalAccessException {
        CostReport obj = costReportMapper.selectByPrimaryKey(banben);
        List<CostReportA> a = costReportAMapper.selectByPrimaryKey(banben);
        List<CostReportB> b = costReportBMapper.selectByPrimaryKey(banben);
        List<CostReportC> c = costReportCMapper.selectByPrimaryKey(banben);
        Map map = new HashMap();
        int i = 1;
        int j = 3;
        int k = 1;
        if (obj !=null) {
            String finishedProductCode2= obj.getFinishedProductCode2();
            if (!StringUtils.isBlank(finishedProductCode2)){
                String finishedProductCode = obj.getFinishedProductCode();
                finishedProductCode+="~"+finishedProductCode2;
                obj.setFinishedProductCode(finishedProductCode);
            }
            map = GetNullPropertyNames.objectToMap(obj);
            CostSignature costSignature = costCommonMapper.selectCostSignatureBycostReportId(banben);
            if (costSignature !=null){
                map.put("xmjl",costSignature.getXmjl());
                map.put("bmjl",costSignature.getBmjl());
                map.put("zjl",costSignature.getZjl());
                map.put("zc",costSignature.getZc());
            }

            for (CostReportA result : a) {
                map.put("A_r" + i + "_ml", result.getLabelCapacity());
                map.put("A_r" + i + "_ra", result.getRatio());
                map.put("A_r" + i + "_actual", result.getActualValue());
                map.put("A_r" + i + "_detail", result.getDetailName());
                map.put("A_r" + i + "_up", result.getUnitPrice());
                map.put("A_r" + i + "_cp", result.getCostPrice());
                map.put("A_r" + i + "_qp", result.getQuotedPrice());
                map.put("A_r" + i + "_bp", result.getBenchmarkPrice());
                i++;
            }
            for (CostReportB result : b) {
                if (result.getWorkerType().equals("1")) {
                    GrfTableVOUtils.costReportBData(map, result, 1);
                } else if (result.getWorkerType().equals("2")) {
                    GrfTableVOUtils.costReportBData(map, result, 2);
                } else if (result.getWorkerType().equals("3")) {
                    GrfTableVOUtils.costReportBData(map, result, j);
                    j++;
                } else if (result.getWorkerType().equals("4")) {
                    GrfTableVOUtils.costReportBData(map, result, 11);
                }
            }
            for (CostReportC result : c) {
                map.put("C_r" + k + "_mountings", result.getMountings());
                map.put("C_r" + k + "_mountings_price", result.getMountingsPrice());
                map.put("C_r" + k + "_mountings_remark", result.getMountingsRemark());
                k++;
            }
            List list = new ArrayList();
            list.add(map);
            return GrfTableVOUtils.success(list, 200, "成功!");
        } else {
            return GrfTableVOUtils.success(null, 500, "没有相关数据!");
        }
    }


    @Override
    public void exportCostReportToExcelService(String costReportId, HttpServletRequest request, HttpServletResponse response) {
        log.info("用户：【"+UserUtils.getSessionUser().getUserName()+"】执行导出单据号为：【"+costReportId+"】的成本报告表的操作");
        //获取成本报告的数据
        CostReport r = costReportMapper.selectByPrimaryKey(costReportId);
        List<CostReportA> a = costReportAMapper.selectByPrimaryKey(costReportId);
        List<CostReportB> b = costReportBMapper.selectByPrimaryKey(costReportId);
        b.forEach((c)->{
            String workerType = c.getWorkerType();
            switch (workerType){
                case "1":
                    c.setWorkerType("配制人工");
                    break;
                case "2":
                    c.setWorkerType("灌装基础人工");
                    break;
                case "3":
                    c.setWorkerType("灌装/组装人工");
                    break;
                case "4":
                   c.setWorkerType("搬运人工");
                    break;
            }
        });
        List<CostReportC> c = costReportCMapper.selectByPrimaryKey(costReportId);
        Map<String, Object> map = new HashMap<String, Object>();
        TemplateExportParams params = new TemplateExportParams(
                "static/templates/costReport.xlsx");
        String salesPkOrg = CommonUtils.getOrgName(r.getSalesPkOrg());
        map.put("salesPkOrg", salesPkOrg==null?"":salesPkOrg);         //标题组织和销售组织
        String pkOrgAccount = CommonUtils.getOrgName(r.getPkOrgAccount());
        map.put("pkOrgAccount", pkOrgAccount==null?"":pkOrgAccount);      //公司账套
        String costReportDate = r.getCostReportDate();
        map.put("costReportDate", costReportDate==null?"":costReportDate);      //日期
        map.put("costReportId", costReportId);      //成本报告单据号
        String clientName = r.getClientName();
        map.put("clientName", clientName==null?"":clientName);      //客户全称
        String clientcode = r.getClientcode();
        map.put("clientcode", clientcode==null?"":clientcode);      //客户编码
        String quotation = r.getQuotation();
        map.put("quotation", quotation==null?"":quotation);      //报价单编号
        String finishedProductCode = r.getFinishedProductCode()==null?"":r.getFinishedProductCode();
        String finishedProductCode2 = r.getFinishedProductCode2()==null?"":r.getFinishedProductCode2();
        map.put("finishedProductCode", finishedProductCode+finishedProductCode2);      //成品编码
        String productName = r.getProductName();
        map.put("productName", productName==null?"":productName);      //产品名称
        String capacity = r.getCapacity();
        map.put("capacity", capacity==null?"":capacity);      //容量规格:
        String costReportUnits = r.getCostReportUnits();
        map.put("costReportUnits",costReportUnits==null?"":costReportUnits);      //单位
        BigDecimal orderQuantity = r.getOrderQuantity();
        map.put("orderQuantity", orderQuantity==null?"":orderQuantity);      //订单量
        BigDecimal fumigationCharge = r.getFumigationCharge();
        map.put("fumigationCharge", fumigationCharge==null?"":fumigationCharge);      //薰蒸費
        BigDecimal cartonCertificate = r.getCartonCertificate();
        map.put("cartonCertificate", cartonCertificate==null?"":cartonCertificate);      //纸箱证明
        BigDecimal customsFee = r.getCustomsFee();
        map.put("customsFee", customsFee==null?"":customsFee);                   //出口报关费用\检测费用
        BigDecimal freight = r.getFreight();
        map.put("freight", freight==null?"":freight);      //运费
        BigDecimal otherCharges = r.getOtherCharges();
        map.put("otherCharges", otherCharges==null?"":otherCharges);      //授权费\顾问费\其他
        BigDecimal laborCostTotal = r.getLaborCostTotal();
        map.put("laborCostTotal", laborCostTotal==null?"":laborCostTotal);    //人工成本合共
        BigDecimal manHourTotal = r.getManHourTotal();
        map.put("manHourTotal", manHourTotal==null?"":manHourTotal);      //人工工时合共
        BigDecimal otherChargesTotal = r.getOtherChargesTotal();
        map.put("otherChargesTotal", otherChargesTotal==null?"":otherChargesTotal);      //其他費用合共
        BigDecimal totalOfPartB = r.getTotalOfPartB();
        map.put("totalOfPartB",totalOfPartB==null?"":totalOfPartB );      //Total of Part B (人工成本+其他費用):
        BigDecimal totalOfPartA = r.getTotalOfPartA();
        map.put("totalOfPartA", totalOfPartA==null?"":totalOfPartA);      //Total of Part A
        BigDecimal totalOfPartC = r.getTotalOfPartC();
        map.put("totalOfPartC", totalOfPartC==null?"":totalOfPartC);      //Total of Part C
        Integer vatexportTaxRate = r.getVatexportTaxRate();
        map.put("vatexportTaxRate",vatexportTaxRate==null?"":vatexportTaxRate );      //t2税款 税率
        BigDecimal vatexportTaxCost = r.getVatexportTaxCost();
        map.put("vatexportTaxCost",vatexportTaxCost==null?"":vatexportTaxCost );      //t2税款 金额
        Integer taxItemRate = r.getTaxItemRate();
        map.put("taxItemRate",taxItemRate==null?"":taxItemRate );      //t3税款 城建率
        BigDecimal taxItemCost = r.getTaxItemCost();
        map.put("taxItemCost", taxItemCost==null?"":taxItemCost);      //t3税款 金额
        BigDecimal accessoriesLossRate = r.getAccessoriesLossRate();
        map.put("accessoriesLossRate",accessoriesLossRate==null?"":accessoriesLossRate );      //总成本-配件消耗率
        BigDecimal totalCost = r.getTotalCost();
        map.put("totalCost", totalCost==null?"":totalCost);      //总成本
        BigDecimal totalCostIncludesTax = r.getTotalCostIncludesTax();
        map.put("totalCostIncludesTax",totalCostIncludesTax==null?"":totalCostIncludesTax );      //总成本含税
        Integer quotedPriceManHour = r.getQuotedPriceManHour();
        map.put("quotedPriceManHour", quotedPriceManHour==null?"":quotedPriceManHour);      //e报价基准工时
        BigDecimal quotedPriceBenchmark = r.getQuotedPriceBenchmark();
        map.put("quotedPriceBenchmark",quotedPriceBenchmark==null?"":quotedPriceBenchmark );      //e报价基准
        BigDecimal realityQuotedPrice = r.getRealityQuotedPrice();
        map.put("realityQuotedPrice", realityQuotedPrice==null?"":realityQuotedPrice);      //F实际报价
        BigDecimal conversionRate = r.getConversionRate();
        map.put("conversionRate", conversionRate==null?"":conversionRate);      //兑换率
        String currencyType = r.getCurrencyType();
        map.put("currencyType",currencyType==null?"":currencyType );      //货币
        BigDecimal conversionMoney = r.getConversionMoney();
        map.put("conversionMoney",conversionMoney==null?"":conversionMoney );      //兑换后金额
        BigDecimal grossMarginMoney = r.getGrossMarginMoney();
        map.put("grossMarginMoney",grossMarginMoney==null?"":grossMarginMoney );      //整体毛利
        BigDecimal grossMarginRate = r.getGrossMarginRate();
        map.put("grossMarginRate", grossMarginRate==null?"":grossMarginRate);      //整套毛利率
        String remark = r.getRemark();
        map.put("remark",remark==null?"":remark );      //原因
        Integer updateType = r.getUpdateType();
        updateType=updateType==null?-1:updateType;
        String updateTypeName="";
        switch (updateType){
            case 1:
                updateTypeName="新报价";
                break;
            case 2:
                updateTypeName="更新成本";
            case 3:
                updateTypeName="3更新报价";
                break;
        }
        map.put("updateType", updateTypeName);      //更新类型(1新报价,2更新成本,3更新报价)
        Integer finishedProduct = r.getFinishedProduct();
        map.put("finishedProduct", finishedProduct==null?"":finishedProduct==1?"是":"否");      //此成品含客料(1是, 2否)
        Integer whetherSupplier = r.getWhetherSupplier();
        map.put("whetherSupplier", whetherSupplier==null?"":whetherSupplier==1?"是":"否");      //此配方是否客料(1是客料,2非客料)
        String exportSales = r.getExportSales();                        //外销单
        map.put("exportSales", exportSales==null?"":exportSales);
        BigDecimal hkdConversion = r.getHKDConversion();                //外销单
        map.put("hkdconversion",hkdConversion==null?"":hkdConversion);
        BigDecimal hkdconversionPrice = r.getHKDConversionPrice();          //外销单
        map.put("hkdconversionPrice",hkdconversionPrice==null?"":hkdconversionPrice);


        map.put("cra", a);                        //A水料价
        map.put("crb", b);      //成本报告单据号
        map.put("crc", c);      //成本报告单据号

        Map<String,Object> modelMap = new HashMap<>();
        modelMap.put(TemplateExcelConstants.FILE_NAME, "成本报告表"+costReportId);
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

    @Override
    public GrfTableVO<Map> getCostReportABC(String banben,String copy) {
        Map map = new HashMap();
        CostReport costReport = costReportMapper.selectByPrimaryKey(banben);
        List<CostReportA> a = costReportAMapper.selectByPrimaryKey(banben);
        List<CostReportB> b = costReportBMapper.selectByPrimaryKey(banben);
        List<CostReportC> c = costReportCMapper.selectByPrimaryKey(banben);
        List<Map<String, String>> bs = costReportBSinglehoursMapper.getCostReportBSinglehoursById(banben);
        List<CostReportBOther> bo = costReportOtherMapper.getCalculateOtherChargesZtTable(banben);
        List<CartonPriceDetailsRecord> ctd = (List<CartonPriceDetailsRecord>)cartonDetailsService.getCartonPriceDetailsRecordByTAndcostReportIdService(new CartonPriceDetailsRecord(banben,1));
        List<CartonPriceDetailsRecord> ctdk = (List<CartonPriceDetailsRecord>)cartonDetailsService.getCartonPriceDetailsRecordByTAndcostReportIdService(new CartonPriceDetailsRecord(banben,2));

        //copy是一个标识符：点击拷贝操作成本报告表按钮会带过来，为了去除id的值用
        if (copy != null) {
            for (int i = 0; i < a.size(); i++) {
                a.get(i).setId(null);
            }
            for (int i = 0; i < b.size(); i++) {
                b.get(i).setId(null);
            }
            for (int i = 0; i < c.size(); i++) {
                c.get(i).setId(null);
            }
        }
        map.put("costReport", costReport);
        map.put("a", a);
        map.put("b", b);
        map.put("c", c);
        map.put("bs",bs);
        map.put("bo",bo);
        map.put("ctd",ctd);
        map.put("ctdk",ctdk);
        List list = new ArrayList();
        list.add(map);
        return GrfTableVOUtils.success(list, 200, "成功!");

    }

    public Object selectSystemMountingsService(String name, DataGridData<String> rows){
        DataGridData< List<Map<String, String>>> dataGrid= new DataGridData<>();
        //处理分页
        DataGridUtils.processingPageData(rows);
        //数据太庞大了，不能是空，，
        if(StringUtils.isBlank(name)){
            name=".....";
        }
        name = "%"+name+"%";
        dataGrid.setTotal(queryManagerMapper.countSystemMountings(name));
        List<Map<String, String>> maps = queryManagerMapper.selectSystemMountings(name, rows);
        dataGrid.setRows(maps);

        return  dataGrid;
    }

    public Object getCurrencyService(String code){
        //当前时间
        LocalDate l= LocalDate.now();
        int year = l.getYear(); //当前年份
        int month = l.getMonthValue();//当前月份
        String cMonth=month+"";
        if (month<10){
            cMonth="0"+cMonth;
        }
        String  startDate=year+"-"+cMonth+"-01";
        String  endDate=year+"-"+cMonth+"-28";
        List<Map<String, String>> currency = queryManagerMapper.getCurrency(startDate, endDate,code);
        if (currency!=null && currency.size()>0){
            return new R(WSC.RESTPONSE_OK,null,currency);
        }else {
            // 处理1月份
            if (month==1){
                month=12;
                year=year-1;
            }else {
                month=month-1;
            }

            cMonth=month+"";
            if (month<10){
                cMonth="0"+cMonth;
            }
            startDate=year+"-"+cMonth+"-01";
            endDate=year+"-"+cMonth+"-28";
            currency = queryManagerMapper.getCurrency(startDate, endDate,code);
            return new R(WSC.RESTPONSE_OK+1,"温馨提示：系统暂时未更新本月的货币率数据，现获取的是上月份的数据，若空上月份也未更新！",currency);
        }

    }

    public Object selectArticlePrice(String peiFangHao){
        try {
            String s = articlePrice.selectArticlePrice(peiFangHao);
            if(s ==null || "".equals(s)){
                return new R(WSC.PRECONDITIONFAILED,"没有此配方号的信息！");
            }
            return new R(WSC.RESTPONSE_OK,null,s);
        }catch (Exception e){
            return new R(WSC.REQUEST_ERROR,"获取失败！");
        }
    }

    public Object selectCostCodingItemService(String costCoding,String pkOrg){
        Map<String,Object> map=new HashMap<>();
        //找成本编码的属性：规格、品名、单位
        List<Map<String, String>> maps = queryManagerMapper.selectCostCodingProperty(costCoding);
        //根据成本编码的主键id获取 所有的配件
        if (maps !=null && maps.size()>0){
            Map<String, String> map1 = maps.get(0);
            map.put("property",map1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String currentDate = simpleDateFormat.format(new Date());
            List<Map<String, String>> pms = queryManagerMapper.selectCostCodingParts(map1.get("PM"), pkOrg, currentDate);
            if (pms !=null && pms.size()>0){
                map.put("parts",pms);
                return  new R(WSC.RESTPONSE_OK,null,map);
            }else {
                return  new R(WSC.RESTPONSE_OK+1,"温馨提示：未找到相关的配件信息！",map);
            }

        }else {
            return  new R(WSC.PRECONDITIONFAILED,"没有相关的成本编码信息！",map);
        }
    }

    @Override
    public CostReport selectByPrimaryKeyService(String costReportId) {

        return costReportMapper.selectByPrimaryKey(costReportId);
    }

    @Override
    public Object getCostPkOrgService(String pkOrg) {
        List<OrgDeptExtend> orgDepts = queryManagerMapper.getCostPkOrg(pkOrg);
        // 存储map
        Map<String, OrgDeptExtend> mapOrgDept = new HashMap<String, OrgDeptExtend>();
        List<OrgDeptExtend> parent = new ArrayList<OrgDeptExtend>();
        for (OrgDeptExtend orgDept : orgDepts) {
            mapOrgDept.put(orgDept.getPkDept(), orgDept);
            if (orgDept.getPkFatherorg().equals("~")) {
                parent.add(orgDept);
            }
        }
        for (OrgDeptExtend orgDept : orgDepts) {
            // 从map中查找到父对象，把自己存进父对象的属性Children中
            OrgDeptExtend orgDeptParent = mapOrgDept.get(orgDept.getPkFatherorg());
            if (orgDeptParent != null) {
                //easyui的关闭
                orgDeptParent.setState("closed");
                orgDeptParent.getChildren().add(orgDept);
            }
        }
        return parent;
    }

    @Override
    public String getDeptNano() {
        OpalUser user = UserUtils.getSessionUser();
        String userDept = user.getUserDept();
        return costReportOtherMapper.getDeptNano(userDept);
    }

    @Override
    public Object getCalculateOtherChargesZtTableDataService(String costReportId) {
        Object ztTable = costReportOtherMapper.getCalculateOtherChargesZtTable(costReportId);
        //处理datagrid不能传过去为null
        if (ztTable==null){
            String[] str={};
            return str;
        }
        return ztTable;
    }

}